package cn.wolfcode.service.impl;

import cn.wolfcode.ann.MyLog;
import cn.wolfcode.domain.Dept;
import cn.wolfcode.domain.DeptLog;
import cn.wolfcode.mapper.DeptMapper;
import cn.wolfcode.mapper.EmpMapper;
import cn.wolfcode.service.DeptLogService;
import cn.wolfcode.service.DeptService;
import cn.wolfcode.web.exception.DataException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional(rollbackFor = Exception.class)
public class DeptServiceImpl implements DeptService {

    @Autowired
    private DeptLogService deptLogService;
    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private DeptMapper deptMapper;

    @Override
//    @MyLog // 表示 : 当前的方法属于目标方法
    public List<Dept> list() {

        return deptMapper.list();
    }


    @Override
    @MyLog // 表示 : 当前的方法属于目标方法
    public void delete(Long id) throws Exception {
        /**
         * catch (Exception e) {
         *             e.printStackTrace();
         *         }
         *         一旦catch 会被 捕获到异常 并且处理
         *         Transactional
         */
        //开启事务
        try {
            deptMapper.delete(id);
//            if (true){
//                throw new Exception("出现异常了");
//            }
            //删除该部门下的所有员工
            empMapper.delByDeptId(id);
        } finally {
            //无论是否发生异常都要进行日志的记录
            DeptLog deptLog = new DeptLog();
            deptLog.setDescription("执行了部门删除的操作,解散的是"+id+"号部门");
            // 开启日志的事务
            deptLogService.add(deptLog);
            //提交日志的事务
        }
        //提交事务
    }

    @Override
    @MyLog
    public void add(Dept dept)  {

        dept.setCreateTime(new Date());
        dept.setUpdateTime(new Date());
        try {
            deptMapper.add(dept);
        } catch (Exception e) {
            throw  new DataException("部门名称已存在");
        }
    }

    @Override
    public Dept selById(Long id) {
        return deptMapper.selById(id);
    }

    @Override
    @MyLog
    public void update(Dept dept) {
        dept.setUpdateTime(new Date());
        deptMapper.update(dept);
    }
}
